/*
 * DllFuncParser.cpp
 *
 *  Created on: 2010-9-15
 *      Author: anod
 */

#include <dlfcn.h>
#include <stddef.h>
#include <stdexcept>
#include <iostream>

#include <Common/Common.hpp>
#include <Module-AppConfig/AppConfig.hpp>
#include <Module-AppData/parser/DllFuncParser.hpp>

namespace AppData
{

using AppConfig::appConfig;
using AppConfig::WidgetConfig;

int DllFuncParser::parse()
{
	// check the policy
	if( appConfig.getPolicy() != WidgetConfig::POLICY_TYPE_SHAREDLIB ) //这个是不可原谅的逻辑错误了
		throw std::logic_error( "call shared-object parser for non-so policy" );

	// open shared object file
	void *h_dll = dlopen( appConfig.getScript().toStdString().c_str(), RTLD_LAZY );
	if( h_dll == NULL )
	{
		std::cout << "dlopen " << "failed with:" << dlerror();	// 做不标准的输出表示错误
		return 0;								// 居然返回0？明明出错了，这是可为用户接受的错误
	}

	parse_func parse_ = (parse_func)dlsym( h_dll, appConfig.getSharedLibFunc() );
	if( parse_ == NULL )
	{
		std::cout << "dlsym " << "failed with:" << dlerror();
		return 0;
	}

	int ret = parse_();
	if( 0 != dlclose( h_dll ) )
	{
		std::cerr << "dlclose " << "failed with:" << dlerror();	// 关闭不成功错误就比较大了
		return 1;
	}
	else return ret;
}

}
